/**
 * 审批基础逻辑
 * */
import http from './request.js'
import dictMixins from './dictMixins.js'
import userMixins from './userMixins.js'
export default {
	name: 'approvalMixins',
	mixins: [dictMixins, userMixins],
	data() {
		let self = this;
		return {
			timeout: null,
			/**
			 * 模块-映射表
			 * @param {String} 		module				模块名称
			 * @param {String}  	pageFetchDataUrl 	模块分页请求数据url
			 * @param {String}  	approvalDetailUrl 	审批详情页面url
			 * @param {String}  	passPre 			审批通过url前缀
			 * @param {String}  	unPassPre 			审批不通过通过url前缀
			 * @param {String}  	appendType 			url拼接链接方式
			 * @param {String}  	itemKey 			实例中取的key
			 * @param {String}  	nameKey 			页面数据row对应展示的名称key
			 * @param {String}  	timeKey 			页面数据row对应展示的时间key
			 * @param {String}  	statusKey 			页面数据row对应展示的状态key
			 * @param {String}  	statusDictCode 		状态判断用的字典code
			 * @param {Function}	customApproval  	自定义审批方法，如果有自定义方法，就不走默认链接逻辑
			 * */
			moduleMap: [{
					module: '教师请假',
					passPre: '/oa/leave/audit/pass',
					unPassPre: '/oa/leave/audit/failed',
					appendType: '?id=',
					itemKey: 'id',
				},
				{
					module: '报销',
					pageFetchDataUrl: '/oa/reimburse/page',
					approvalDetailUrl: '/modules/reimbursement/reimbursementDetail',
					passPre: '/oa/reimburse/audit/pass',
					unPassPre: '/oa/reimburse/audit/failed',
					appendType: '?id=',
					itemKey: 'id',
					menuProp: ['applicantName', 'applyDate', 'applyStatus'],
					tit: ['申请人', '申请日期', '状态'],
				},
				{
					module: '用车',
					pageFetchDataUrl: '/oa/carAudit/page',
					approvalDetailUrl: '/modules/car/applyDetail',

					statusDictCode: 'dict_car_apply_status',
					async customApproval(item, preUrlKey) {
						let isPass = preUrlKey == 'passPre'
						let params = {
							id: item.id,
							applyStatus: isPass ? 3 : 2
						}
						let resp = await http.post({
							url: '/oa/carAudit/approval',
							data: params
						});
						self.handleSuccess();
					},
					menuProp: ['applicant', 'applyDate', 'carType', 'applyStatus'],
					tit: ['申请人', '申请日期', '车辆型号', '状态'],
				},
				{
					module: '会议',
					pageFetchDataUrl: '/oa/meetingManage/page',
					approvalDetailUrl: '/modules/meeting/meetingDetail',
					passPre: '/oa/meetingManage/pass',
					unPassPre: '/oa/meetingManage/fail',
					appendType: '?id=',
					itemKey: 'id',

					menuProp: ['teacherName', 'createTime', 'meetingDate', 'applyStatus'],
					tit: ['申请人', '申请日期', '会议日期', '状态'],
				},
				{
					module: '用章',
					pageFetchDataUrl: '/oa/sealApply/pageApproval',
					approvalDetailUrl: '/modules/seal/detail',

					async customApproval(item, preUrlKey) {
						let isPass = preUrlKey == 'passPre'
						let params = {
							id: item.id,
							applyStatus: isPass ? 2 : 3
						}
						let resp = await http.post({
							url: '/oa/sealApply/approval',
							data: params
						});
						self.handleSuccess();
					},
					menuProp: ['applicantTeacherName', 'applyDate', 'sealName', 'applyStatus'],
					tit: ['申请人', '申请日期', '印章名称', '状态'],
				},
				{
					module: '报修',
					pageFetchDataUrl: '/oa/wechat/repairsAudit/page',
					approvalDetailUrl: '/modules/fixed/fixedDetail',
					statusDictCode: "dict_oa_repairs",
					async customApproval(item, preUrlKey) {
						let isPass = preUrlKey == 'passPre'
						let resp = await http.post({
							url: `/oa/wechat/repairsAudit/approval/${item.id}`,
						});
						self.handleSuccess();
					},
					menuProp: ['applicantTeacherName', 'applyDate', 'applyStatus'],
					tit: ['申请人', '申请日期', '状态'],
				},
				{
					module: '用餐',
					pageFetchDataUrl: '/oa/wechat/dinnerAudit/page',
					approvalDetailUrl: '/modules/meal/detail',
					async customApproval(item, preUrlKey) {
						let isPass = preUrlKey == 'passPre'
						let params = {
							// 通过：2  不通过：3
							applyStatus: isPass ? 2 : 3,
							id: item.id
						}
						let resp = await http.post({
							url: `/oa/wechat/dinnerAudit/approval`,
							data: params
						});
						self.handleSuccess();
					},
					menuProp: ['applicant', 'applyDate', 'applyStatus'],
					tit: ['申请人', '申请时间', '状态'],
				},
				{
					module: '调代课',
					pageFetchDataUrl: '/edu/wechat/classCourseChangeAudit/page',
					approvalDetailUrl: `/modules/substituteCoruse/changeCoruseDetail`,
					changePath: "changeCoruseDetail",

					async customApproval(item, preUrlKey) {
						let isPass = preUrlKey == 'passPre'
						let params = {
							// 通过：2  不通过：3
							applyStatus: isPass ? 2 : 3,
							id: item.id
						}
						let resp = await http.post({
							url: `/edu/wechat/classCourseChangeAudit/approval`,
							data: params
						});
						self.handleSuccess();
					},
					menuProp: ['teacherName', 'applyDate', 'changeType', 'applyStatus'],
					tit: ['姓名', '申请时间', '类型', '状态'],
				},
			]
		}
	},
	methods: {
		//搜索防抖
		debounce(func, wait) {
			let context = this
			if (this.timeout) clearTimeout(this.timeout)
			this.timeout = setTimeout(() => {
				context[func]()
			}, wait)
		},
		/**
		 * 判断审批功能是否能展示
		 * item.detailType = approval时展示 并且当前是待审核状态
		 * @param {String} statusKey 判断审批状态的key
		 * */
		getApprovalShow(statusKey) {
			let itemData = this.itemData;
			let auditVos = this.auditVos;
			let user = this.user;
			let isAuditer = true;
			if (auditVos.length > 0) {
				let lastNumber = auditVos[auditVos.length - 1].auditJobNumber;
				let nowUserNumber = user.number;
				// if (lastNumber != nowUserNumber) {	//最后审批节点不是当前用户,不能审批
				// 	isAuditer = false;
				// }
				if (lastNumber.indexOf(nowUserNumber) < 0) { //最后审批节点不是当前用户,不能审批
					isAuditer = false;
				}
			}
			let canApproval = itemData.detailType == 'approval' && itemData[statusKey] == 1 && isAuditer;
			return canApproval;
		},
		/**
		 * 获取模块映射表中的对应模块
		 * */
		getModule(module) {
			let findOne = this.moduleMap.filter(item => {
				return item.module == module
			})[0]
			return findOne;
		},
		/**
		 * 处理接口请求逻辑
		 * 如果有自定义请求方法，使用自定义方法
		 * 
		 * @param {String} preUrlKey 前缀地址key
		 * */
		async handleApprovalFetch(module, item, preUrlKey) {
			let findOne = this.getModule(module);
			if (!findOne) return;
			if (findOne.customApproval) {
				await findOne.customApproval(item, preUrlKey);
				return;
			}
			let {
				appendType,
				itemKey
			} = findOne;
			let url = findOne[preUrlKey] + appendType + item[itemKey];
			let resp = await http.get({
				url
			});
			this.handleSuccess();
		},
		/**
		 * 审批通过
		 * @param {String} module 模块
		 * @param {Object} item 实例对象
		 * */
		async pass(module, item) {
			this.handleApprovalFetch(module, item, 'passPre');
		},
		/**
		 * 审批不通过
		 * @param {String} module 模块
		 * @param {Object} item 实例对象
		 * */
		async unpass(module, item) {
			this.handleApprovalFetch(module, item, 'unPassPre');
		},
		/**
		 * 处理操作成功后逻辑
		 * @param {String} pageUrl 成功后跳转的页面
		 * */
		handleSuccess(pageUrl) {
			uni.showToast({
				title: '操作成功',
				icon: 'none',
				success() {

					let pages = getCurrentPages();
					console.log(pages)
					uni.navigateBack();
				}
			});
		},
		/**
		 * 审批页面通用获取数据方法
		 * @param {String} module 				模块
		 * @param {String} config 				配置项
		 * */
		async pageFetchData(module) {
			let self = this
			let findOne = this.getModule(module);
			let propsData = {}
			if (!findOne) return;
			if (findOne.menuProp) {
				this.menuInfo.base.menuProp = findOne.menuProp
				this.menuInfo.base.tit = findOne.tit
				findOne.menuProp.forEach(item => {
					propsData[item] = ''
				})
			}
			let {
				statusDictCode
			} = findOne;
			if (!statusDictCode) statusDictCode = 'dict_apply_status';
			let resp = await http.post({
				url: findOne.pageFetchDataUrl,
				data: {
					wechatHandleStatus: this.leaveStatusStr,
					...this.pageParams,
					queryName: self.name
				}
			});
			let list = this.calTypeResp(resp);
			this.menuInfo.list = list.map(item => {
				item.detailType = 'approval';
				if (propsData) {
					Object.keys(propsData).forEach(function(key) {
						switch (key) {
							case 'changeType':
								propsData[key] = self.getDictNameWithCodeAndValue('dict_course_change_type', item[key])
								break;
							case 'applyStatus':
								propsData[key] = self.getDictNameWithCodeAndValue(statusDictCode, item[key])
								break;
							case 'applyDate':
								propsData[key] = item[key].substring(0, 10)
								break;
							case 'meetingDate':
								propsData[key] = item[key].substring(0, 10)
								break;
							case 'createTime':
								propsData[key] = item[key].substring(0, 10)
								break;
							default:
								propsData[key] = item[key]
								break;
						}
					});
				}
				if (findOne.changePath) {
					if (item.changeType == 1) {
						findOne.approvalDetailUrl = '/modules/substituteCoruse/changeCoruseDetail'
					} else if (item.changeType == 2) {
						findOne.approvalDetailUrl = '/modules/substituteCoruse/changeTeacherDetail'
					} else {
						findOne.approvalDetailUrl = '/modules/substituteCoruse/stopCoruseDetail'
					}
				}
				let obj = {
					url: `${findOne.approvalDetailUrl}?data=${JSON.stringify(item)}`,
					data: item,
					...propsData
				};
				return obj;


			})
			this.isInit = true;
		},
		/**
		 * 计算不同类型的数据
		 * 1. 加载更多状态
		 * 2. 待审批、已审批数据数量
		 * @param {Object} resp 接口数据返回
		 * @param {String} statusKey 做状态判断的key
		 * @return {Array} 当前状态的数据
		 * */
		calTypeResp(resp, statusKey) {
			let list = resp.result.rows || resp.result.records;
			// "加载更多"组件 展示状态判断
			if (list.length < this.pageParams.pageSize || list.length == 0) {
				this.menuInfo.base.loadMore = false;
			}
			if (this.leaveStatusStr == 'N') {
				this.pendingApproval = list.length
				this.approved = ''
			} else {
				this.pendingApproval = ''
				this.approved = list.length
			}
			return list;
		}
	}
}
